package com.nekonomics
package persistence.repository

import domain.entity.Address
import utils.SqlUtil

import doobie.*
import doobie.implicits.*
import zio.*

trait AddressRepo {
  def findByUserId(userId: Long): ConnectionIO[List[Address]]
  def findById(id: Long): ConnectionIO[Option[Address]]
  def getById(id: Long): ConnectionIO[Address] = findById(id).map(_.get)
}

object AddressRepo {
  val live: ULayer[AddressRepo] = ZLayer.succeed(new AddressRepoLive)
}


private case class AddressRepoLive() extends AddressRepo {


  override def findById(id: Long): doobie.ConnectionIO[Option[Address]] = {
    SqlUtil.selectFromWhereOpt[Address](Some(fr"id = $id"))
      .query[Address]
      .option
  }
  
  override def findByUserId(userId: Long): ConnectionIO[List[Address]] = {
    SqlUtil.selectFromWhereOpt[Address](Some(fr"user_id = $userId"))
      .query[Address]
      .to[List]
  }
}